#include "BlockQueue.hpp"
#include "Task.hpp"
#include <iostream>
#include <time.h>
#include <pthread.h>
#include <unistd.h>

void *Consumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task>*>(args);
    while (true)
    {
        // 消费
        Task t = bq->pop();
        // 计算
        t();  // t.run()
        std:: cout << "处理任务: " << t.GetTask() << "运算结果是: " 
        << t.GetResult() << " thread id: " << pthread_self() << std::endl;
    }
    return nullptr;

    // BlockQueue<int> *bq = static_cast<BlockQueue<int>*>(args); 
    // while (true)
    // {
    //     // 消费
    //     int data = bq->pop();
    //     std::cout << "消费了一个数据: " << data << std::endl;
    //     sleep(1);
    // }
    // return nullptr;
}

void *Productor(void *args)
{
    int len = opers.size();
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task>*>(args);

    while (true)
    {
        // 模拟生产者生产数据
        int data1 = rand() % 10 + 1; 
        usleep(10);
        int data2 = rand() % 10;
        char op = opers[rand() % len];
        Task t(data1, data2, op);

        // 生产
        bq->push(t);
        std::cout << "生产了一个任务: " << t.GetTask() 
        << " thread id: " << pthread_self() << std::endl;
        sleep(1);
    }
    return nullptr;

    // BlockQueue<int> *bq = static_cast<BlockQueue<int>*>(args);
    // int data = 0;
    // while (true)
    // {
    //     // 生产
    //     ++data;
    //     bq->push(data);
    //     std::cout << "生成了一个数据: " << data << std::endl;
    //     sleep(1);
    // }
    // return nullptr;
}

int main()
{
    srand(time(nullptr));
    // BlockQueue<int> *bq = new BlockQueue<int>();
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    
    pthread_t c[3], p[5];
    for (int i = 0; i < 3; ++i)  pthread_create(c + i, nullptr, Productor, bq);
    for (int i = 0; i < 5; ++i)  pthread_create(p + i, nullptr, Consumer, bq);

    for (int i = 0; i < 3; ++i)  pthread_join(c[i], nullptr);
    for (int i = 0; i < 5; ++i)  pthread_join(p[i], nullptr);
    delete bq;

    return 0;
}
